import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Input,
  Select,
  Button,
  Tag,
  Space,
  Typography,
  Row,
  Col,
  Statistic,
  message,
} from 'antd';
import {
  SearchOutlined,
  PlusOutlined,
  GiftOutlined,
  StarOutlined,
} from '@ant-design/icons';
import { Link } from 'react-router-dom';
import { getRequests } from '../../api/request';
import { Request, PageResult } from '../../types';
import { formatDateTime } from '../../utils/format';

const { Search } = Input;
const { Option } = Select;
const { Title, Text } = Typography;

const RequestList: React.FC = () => {
  const [requests, setRequests] = useState<Request[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [filters, setFilters] = useState({
    keyword: '',
    categoryId: '',
    status: '',
  });

  const categories = [
    { value: '', label: '全部分类' },
    { value: 1, label: '电影' },
    { value: 2, label: '电视剧' },
    { value: 3, label: '音乐' },
    { value: 4, label: '软件' },
    { value: 5, label: '游戏' },
    { value: 6, label: '电子书' },
    { value: 7, label: '动漫' },
    { value: 8, label: '其他' },
  ];

  const statusOptions = [
    { value: '', label: '全部状态' },
    { value: 0, label: '进行中' },
    { value: 1, label: '已完成' },
    { value: 2, label: '已关闭' },
  ];

  useEffect(() => {
    fetchRequests();
  }, [pagination.current, pagination.pageSize, filters]);

  const fetchRequests = async () => {
    try {
      setLoading(true);
      const response = await getRequests({
        current: pagination.current,
        size: pagination.pageSize,
        ...filters
      });

      if (response.code === 200) {
        setRequests(response.data.records);
        setPagination(prev => ({
          ...prev,
          total: response.data.total,
        }));
      }
    } catch (error) {
      console.error('获取求种列表失败:', error);
      message.error('获取求种列表失败');
    } finally {
      setLoading(false);
    }
  };

  const getStatusTag = (status: number) => {
    switch (status) {
      case 0:
        return <Tag color="processing">进行中</Tag>;
      case 1:
        return <Tag color="success">已完成</Tag>;
      case 2:
        return <Tag color="default">已关闭</Tag>;
      default:
        return <Tag>未知</Tag>;
    }
  };

  const columns = [
    {
      title: '求种信息',
      dataIndex: 'title',
      key: 'title',
      render: (title: string, record: Request) => (
        <div>
          <Link to={`/requests/${record.id}`}>
            <Text strong>{title}</Text>
          </Link>
          <div style={{ marginTop: 4 }}>
            <Space split={<span>•</span>}>
              <Tag color="blue">{record.categoryName || '未分类'}</Tag>
              <Text type="secondary">
                发起者: {record.username}
              </Text>
            </Space>
          </div>
        </div>
      ),
    },
    {
      title: '悬赏魔力值',
      dataIndex: 'rewardPoints',
      key: 'rewardPoints',
      width: 120,
      render: (points: number) => (
        <Text strong style={{ color: '#fa8c16' }}>
          <StarOutlined /> {points}
        </Text>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: number) => getStatusTag(status),
    },
    {
      title: '发布时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 150,
      render: (time: string) => formatDateTime(time),
    },
    {
      title: '完成时间',
      dataIndex: 'filledAt',
      key: 'filledAt',
      width: 150,
      render: (time: string) => time ? formatDateTime(time) : '-',
    },
    {
      title: '完成者',
      dataIndex: 'filledBy',
      key: 'filledBy',
      width: 100,
      render: (user: string) => user || '-',
    },
  ];

  return (
    <div>
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="求种总数"
              value={pagination.total}
              prefix={<GiftOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="进行中"
              value={requests.filter(r => r.status === 0).length}
              prefix={<GiftOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已完成"
              value={requests.filter(r => r.status === 1).length}
              prefix={<GiftOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总悬赏"
              value={requests.reduce((sum, r) => sum + (r.rewardPoints || 0), 0)}
              prefix={<StarOutlined />}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
      </Row>

      <Card>
        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
          <Row gutter={16} align="middle">
            <Col span={8}>
              <Search
                placeholder="搜索求种标题..."
                allowClear
                enterButton={<SearchOutlined />}
                value={filters.keyword}
                onChange={(e) => setFilters(prev => ({ ...prev, keyword: e.target.value }))}
                onSearch={() => {
                  setPagination(prev => ({ ...prev, current: 1 }));
                  fetchRequests();
                }}
              />
            </Col>
            <Col span={4}>
              <Select
                style={{ width: '100%' }}
                placeholder="选择分类"
                value={filters.categoryId}
                onChange={(value) => setFilters(prev => ({ ...prev, categoryId: value }))}
              >
                {categories.map(cat => (
                  <Option key={cat.value} value={cat.value}>{cat.label}</Option>
                ))}
              </Select>
            </Col>
            <Col span={4}>
              <Select
                style={{ width: '100%' }}
                placeholder="状态筛选"
                value={filters.status}
                onChange={(value) => setFilters(prev => ({ ...prev, status: value }))}
              >
                {statusOptions.map(opt => (
                  <Option key={opt.value} value={opt.value}>{opt.label}</Option>
                ))}
              </Select>
            </Col>
            <Col span={4}>
              <Button type="primary" block onClick={fetchRequests}>
                刷新
              </Button>
            </Col>
            <Col span={4}>
              <Link to="/requests/new">
                <Button type="primary" block icon={<PlusOutlined />}>
                  发起求种
                </Button>
              </Link>
            </Col>
          </Row>

          <Table
            columns={columns}
            dataSource={requests}
            rowKey="id"
            loading={loading}
            pagination={{
              current: pagination.current,
              pageSize: pagination.pageSize,
              total: pagination.total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => 
                `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
              onChange: (page, pageSize) => {
                setPagination(prev => ({
                  ...prev,
                  current: page,
                  pageSize: pageSize || 20,
                }));
              },
            }}
          />
        </Space>
      </Card>
    </div>
  );
};

export default RequestList; 